// BOM表单组件 - 用于新增/编辑/查看BOM信息





<script setup lang="ts">
// 导入所需的Vue组件和工具函数
import { ref, reactive, defineProps, defineEmits, watch, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Money, Box, Van, SetUp, More } from '@element-plus/icons-vue'
const { dialog, onShow, onClose } = useDialog()
// 导入相关类型定义和API
import { specificationDetailQuery } from '@/api/specificationDetail/type.ts'
import { getSpecificationDetailApi } from '@/api/specificationDetail/index.ts'

import { Quotation, QuotationListParam } from '@/api/quotation/type.ts'
import {
  getListApi,
  getBOMList,
  getDetailByIdApi,
  addApi,
  editApi,
} from '@/api/quotation/index.ts'

import ArchiveSelector from '@/components/common/ArchiveSelector.vue'
// 引入统一格式化工具
import { formatPrice, formatNumber } from '@/utils/formatter'

// 定义组件属性
const props = defineProps<{
  Id?: number //  ID，编辑时传入
  mode: string // 组件模式：add/edit/view
}>()



// 定义组件事件
const emit = defineEmits(['save-success', 'cancel'])

// 表单ref，用于表单验证
const formRef = ref<FormInstance>()

// 初始化表单数据
const formData = reactive<Quotation>({
  id: undefined, // 报价单ID
  parentId: undefined, // 父报价单ID（如果有的话）
  name: undefined, // 名称
  specification: undefined, // 规格
  material: undefined, // 材质
  width: undefined, // 宽度
  height: undefined, // 高度
  quantity: undefined, // 数量
  unit: undefined, // 单位，如"个"、"米"、"箱"等
  color: undefined, // 颜色
  colorPrice: 0,
  remark: undefined, // 备注
  unitPrice: undefined, // 含税单价
  unitWeight: undefined, // 单重
  kgPrice: undefined, // 公斤价
  totalPrice: undefined, // 总价
  totalWeight: undefined, // 总重
  projectId: undefined, // 客户
  projectName: undefined, // 客户
  packingPrice: undefined,  // 包装费
  transportationPrice:  undefined,  // 运输费
  implementationPrice:  undefined,  // 实施费
  otherPrice:  undefined, // 其他费用
  packingPriceCoefficient: undefined, // 包装费系数
  materialModel: undefined,
  remark1: undefined,
  remark2: undefined,
  remark3: undefined,
  fastenerType: undefined,
  activate: undefined, // 激活状态
  detailMap: undefined, // 费用详情数据(JSON字符串)
  map: undefined, // 解析后的费用详情数据
  children: [], // 空数组初始化  计件产品配置
})

// 保存从后端获取的原始数据，用于包装费计算
const originalUnitPrice = ref<number>(0)
const originalTotalPrice = ref<number>(0)

// 根据母件信息查询子件配置
const specificationDetail = reactive<specificationDetailQuery>({
  materialName: undefined, // 物料
  specification: undefined, // 规格
  length: undefined, // 高度
  breadth: undefined, // 宽度
  number: undefined, // 数量
  materialType: undefined, // 材质
  colorPrice: 0,
  remark1: undefined,
  remark2: undefined,
  remark3: undefined,
  fastenerType: undefined,
})



//表单校验规则
const rules = {
  name: [{required: true, message: '请输入名称', trigger: 'change'}],
  color: [{required: true, message: '请选择颜色', trigger: 'change'}],
  projectName: [{required: true, message: '请选择项目'}],
}



// 提交表单
const submitForm = async () => {
  if (props.mode === 'view') return // 查看模式不允许提交
  try {
    // 表单验证
    await formRef.value?.validate()
    
    // 检查物料清单中是否有数量大于0但含税单价等于0的情况
    const invalidItems = formData.children?.filter((child: any) => {
      const quantity = Number(child.quantity) || 0
      const unitPrice = Number(child.unitPrice) || 0
      return quantity > 0 && unitPrice === 0
    }) || []
    
    if (invalidItems.length > 0) {
      // 构建警告信息
      const warningItems = invalidItems.map((item: any, index: number) => 
        `${index + 1}. ${item.name || '未知物料'} (数量: ${item.quantity}, 含税单价: 0)`
      ).join('\n')
      
      const warningMessage = `检测到以下物料数量大于0但含税单价为0，是否确认保存？\n\n${warningItems}`
      
      // 使用Element Plus的确认对话框
      try {
        await ElMessageBox.confirm(warningMessage, '保存确认', {
          confirmButtonText: '确认保存',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: false,
          customClass: 'custom-message-box'
        })
      } catch (confirmError) {
        // 用户点击取消，不执行保存
        return
      }
    }
    
    // 在保存前，将children中的map数据序列化并保存到detailMap字段
    if (formData.children && formData.children.length > 0) {
      formData.children.forEach((child: any) => {
        if (child.map && Object.keys(child.map).length > 0) {
          // 将map数据序列化为JSON字符串保存到detailMap字段
          child.detailMap = JSON.stringify(child.map)
        }
      })
    }
    
    console.log(props.mode + '提交数据：' + formData)
    if (props.mode === 'add') {
      // 调用保存API
      await addApi(formData)
    }
    if (props.mode === 'edit') {
      // 调用保存API
      await editApi(formData)
    }
    ElMessage.success('保存成功')
    emit('save-success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('保存失败')
  }
}

function printPage() {
  window.print();
}
// 取消操作
const cancel = () => {
  emit('cancel')
}

// 计算包装费并更新最终总价  
const calculateFinalPrice = () => {
  if (!originalTotalPrice.value || !formData.totalWeight) {
    return
  }
  
  // 原始总价（从后端获取的基础总价）
  const originalPrice = originalTotalPrice.value
  // 总重量
  const totalWeight = Number(formData.totalWeight) || 0
  // 包装费系数
  const packingCoefficient = Number(formData.packingPriceCoefficient) || 0
  
  // 计算包装费：总重 × 包装费系数
  const packingFee = totalWeight * packingCoefficient
  
  // 最终总价 = 原始总价 + 包装费
  const finalTotalPrice = originalPrice + packingFee
  
  // 更新总价，含税单价保持不变
  formData.totalPrice = Number(finalTotalPrice.toFixed(2))
}

// 监听bomId变化,当编辑时加载BOM详情
watch(
  () => props.Id,
  async (newVal) => {
    console.log(props.Id)
    if (newVal) {
      try {
        const res = await getDetailByIdApi(newVal)
        formData.materialModel=res.data.specification
        console.log(res.data)
        if (res?.data) {
          Object.assign(formData, res.data) // 加载详情数据到表单
          selectedProject.value = {
            id: res.data.projectId,
            name: res.data.projectName || '',
          } as ProjectDocument
          
          // 处理children数据（如果存在）
          if (res.data.children && res.data.children.length > 0) {
            formData.children = res.data.children.map((item: any) => ({
              id: item.id,
              parentId: item.parentId,
              name: item.name,
              specification: item.specification,
              material: item.material,
              height: item.height,
              width: item.width,
              quantity: item.quantity,
              unitPrice: item.unitPrice,
              unitWeight: item.unitWeight,
              kgPrice: item.kgPrice,
              totalPrice: item.totalPrice,
              totalWeight: item.totalWeight,
              // 优先使用保存的detailMap数据，如果没有则使用map字段
              map: item.detailMap ? JSON.parse(item.detailMap) : (item.map || {}),
              detailMap: item.detailMap, // 保存原始的JSON字符串
            }))
          }
          
          // 保存原始数据用于包装费计算
          originalUnitPrice.value = Number(res.data.unitPrice) || 0
          
          // 计算原始总价（从数据库加载时，需要减去包装费）
          const totalPrice = Number(res.data.totalPrice) || 0
          const totalWeight = Number(res.data.totalWeight) || 0
          const packingCoefficient = Number(res.data.packingPriceCoefficient) || 0
          const packingFee = totalWeight * packingCoefficient
          originalTotalPrice.value = totalPrice - packingFee
          
          // 检查核价模块状态：如果为失效状态且当前是编辑模式，则自动切换到查看模式
          // 注：activate字段是Integer类型（0或1），需要转换为数字进行比较
          console.log('当前模式:', props.mode)
          console.log('activate字段值:', res.data.activate, '类型:', typeof res.data.activate)
          console.log('Number转换后:', Number(res.data.activate))
          console.log('完整数据:', res.data)
          
          if (props.mode === 'edit' && Number(res.data.activate) !== 1) {
            console.log('核价模块已失效，自动切换到查看模式')
            // 通过emit通知父组件切换到查看模式
            emit('cancel')
            // 显示提示信息
            ElMessage.warning('该核价模块已失效，不允许编辑操作')
            return
          }
          
          // 查看模式下不重新查询价格，保持数据库中的价格
          if (props.mode === 'view') {
            console.log('查看模式，保持原有价格不重新查询')
          } else {
            console.log('编辑模式，允许重新计算价格')
          }
        } else {
          // 新增模式下才重新查询价格
          getSpecificationDetail(true)
        }
      } catch (error) {
        console.error('获取BOM详情失败:', error)
      }
    }
  },
  { immediate: true }
)

// 专门监听数量变化，确保总价总重正确更新
watch(
  () => formData.quantity,
  (newQuantity, oldQuantity) => {
    // 避免初始化时的无效触发
    if (newQuantity === oldQuantity || !newQuantity || newQuantity <= 0) {
      return
    }
    
    console.log('数量变化:', { from: oldQuantity, to: newQuantity })
    
    // 如果有含税单价和单重，直接计算总价和总重
    if (formData.unitPrice && formData.unitWeight) {
      // 重新计算总重和基础总价
      const quantity = Number(newQuantity) || 0
      const unitPrice = Number(formData.unitPrice) || 0
      const unitWeight = Number(formData.unitWeight) || 0
      
      // 更新总重和基础总价
      formData.totalWeight = unitWeight * quantity
      
      // 保存基础总价用于包装费计算
      originalTotalPrice.value = unitPrice * quantity
      
      // 重新计算最终总价（包含包装费）
      calculateFinalPrice()
      
      console.log('数量变化后重新计算完成:', {
        quantity,
        unitPrice,
        unitWeight,
        totalWeight: formData.totalWeight,
        totalPrice: formData.totalPrice
      })
    } else if (formData.name && formData.specification && formData.height && formData.material) {
      // 如果有基础信息但没有价格，重新查询
      console.log('数量变化且有基础信息，重新查询价格')
      getSpecificationDetail(true)
    }
  }
)

// 监听包装费系数变化，自动重新计算总价
watch(
  () => formData.packingPriceCoefficient,
  (newVal) => {
    if (newVal !== undefined && originalTotalPrice.value && formData.totalWeight) {
      calculateFinalPrice()
    }
  }
)

// 当前激活的tab页
const activeTab = ref('materials')

// 计算当前包装费（用于显示）
const currentPackingFee = computed(() => {
  const totalWeight = Number(formData.totalWeight) || 0
  const packingCoefficient = Number(formData.packingPriceCoefficient) || 0
  return totalWeight * packingCoefficient
})

// BOM列表数据
const bomList = ref<any[]>([])
const bomLoading = ref(false)

// 获取BOM列表数据
const loadBOMList = async () => {
  bomLoading.value = true
  try {
    const res = await getBOMList()
    if (res && res.data) {
      bomList.value = res.data
    }
  } catch (error) {
    console.error('获取BOM列表失败:', error)
    ElMessage.error('获取BOM列表失败')
  } finally {
    bomLoading.value = false
  }
}

// 物料选择改变时触发规格详情查询
const handleMaterialChange = () => {
  // 选择物料后自动触发规格详情查询
  getSpecificationDetail(true)
}

// 物料名称输入框失去焦点时自动匹配选择
const handleMaterialAutoSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const inputValue = target?.value?.trim()
  
  if (inputValue && bomList.value.length > 0) {
    // 查找完全匹配的选项
    const matchedItem = bomList.value.find(item => 
      item.materialName === inputValue
    )
    
    if (matchedItem && formData.name !== matchedItem.materialName) {
      // 自动选择匹配的选项
      formData.name = matchedItem.materialName
      // 触发变更事件
      handleMaterialChange()
    }
  }
}

// 组件挂载时获取BOM列表
onMounted(() => {
  loadBOMList()
  // 新增模式下加载默认颜色
  loadDefaultColor()
})

// 加载默认颜色（新增模式下自动设置第一个颜色）
const loadDefaultColor = async () => {
  if (props.mode === 'add' && !formData.color) {
    try {
      const res = await getColorListApi({
        colorCode: '',
        colorName: '',
        isActive: 0, // 只获取启用的颜色
        page: 1,
        limit: 1
      })
      if (res && res.data && res.data.list && res.data.list.length > 0) {
        const firstColor = res.data.list[0]
        formData.color = firstColor.colorName
        selectedColor.value = firstColor
        console.log('自动设置默认颜色:', firstColor.colorName)
      }
    } catch (error) {
      console.error('加载默认颜色失败:', error)
    }
  }
}

// 根据母件信息查询子件配置
const getSpecificationDetail = async (forceQuery = false) => {
  // 如果是查看模式且不是强制查询，则跳过（编辑模式允许重新计算）
  if (props.Id && props.mode === 'view' && !forceQuery) {
    console.log('查看模式，跳过自动价格查询')
    return
  }
  // 验证必要字段是否为空
  if (!formData.name || !formData.specification || !formData.height ||  !formData.quantity||  !formData.material) {
    console.log('必要字段为空，跳过查询')
    return
  }

  // 查询条件
  specificationDetail.materialName = formData.name
  specificationDetail.specification = formData.specification
  specificationDetail.length = formData.height
  specificationDetail.breadth = formData.width
  specificationDetail.number = formData.quantity
  specificationDetail.colorPrice = formData.colorPrice
  specificationDetail.materialType = formData.material
  specificationDetail.remark1 = formData.remark1
  specificationDetail.remark2 = formData.remark2
  specificationDetail.remark3 = formData.remark3
  specificationDetail.fastenerType = formData.fastenerType
  try {
    const res = await getSpecificationDetailApi(specificationDetail)
    console.log(res)
    if (res?.data) {
      formData.unitPrice = res.data.price
      formData.unitWeight = res.data.weight
      formData.kgPrice = res.data.kilogramPrice
      formData.totalPrice = res.data.allPrice
      formData.totalWeight = res.data.allWeight
      
      // 保存原始数据，用于包装费计算
      originalUnitPrice.value = Number(res.data.price) || 0
      originalTotalPrice.value = Number(res.data.allPrice) || 0
      
      // 计算包装费并更新总价
      calculateFinalPrice()
      formData.children = res.data.children.map((item: any, index: number) => ({
        id: formData.children[index]?.id, // 获取原本 formData.children 中的 id
        parentId: formData.children[index]?.parentId, // 获取原本 formData.children 中的 parentId
        name: item.materialName,
        specification: item.materialSpecifications,
        material: item.materialType,
        height: item.height,
        width: item.width,
        quantity: item.number,
        unitPrice: item.price,
        unitWeight: item.weight,
        kgPrice: item.kilogramPrice,
        totalPrice: item.allPrice,
        totalWeight: item.allWeight,
        map: item.map,
      }))

      // 检查是否有基础数据维护警告
      if(res.data.dataMaintainWarnings && res.data.dataMaintainWarnings.length > 0) {
        const warningMsg = '基础数据维护提醒：\n' + res.data.dataMaintainWarnings.join('\n')
        ElMessage.warning({
          message: warningMsg,
          duration: 10000,  // 延长显示时间
          showClose: true,
          dangerouslyUseHTMLString: false
        })
        console.warn('【基础数据维护提醒】', res.data.dataMaintainWarnings)
      }
    } else {
      ElMessage.error('暂未查询到该配置')
    }
  } catch (error: any) {
    console.log(error)
    
    // 处理后端返回的基础数据维护提醒异常
    let errorMessage = '暂未查询到该配置'
    if (error?.response?.data?.message) {
      errorMessage = error.response.data.message
    } else if (error?.message) {
      errorMessage = error.message
    }
    
    if (errorMessage.includes('【基础数据维护提醒】')) {
      ElMessage.warning({
        message: errorMessage,
        duration: 12000,  // 基础数据提醒延长显示时间
        showClose: true,
        dangerouslyUseHTMLString: false
      })
      console.warn('【基础数据维护提醒】', errorMessage)
    } else {
      ElMessage.error({
        message: errorMessage,
        duration: 5000,
        showClose: true
      })
    }
  } finally {
  }
}

// 定义详情数据的接口
interface DetailData {
  [key: string]: number | string
}

// 当前显示的详情数据
const currentDetailData = ref<DetailData | null>(null)

// 查询显示明细
const viewDetail = async (index: number) => {
  const detailData = formData.children[index].map as DetailData
  console.log('详情数据:', detailData)
  
  // 检查是否有详情数据
  if (!detailData || Object.keys(detailData).length === 0) {
    ElMessage.warning('该项目暂无详细费用明细数据')
    return
  }
  
  dialog.title = '费用详情'
  dialog.width = 700
  dialog.height = 350
  dialog.visible = true
  currentDetailData.value = detailData
}

import { getListApi as getColorListApi } from '@/api/color'
import type { Color } from '@/api/color/type'
import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog.ts'
import {getProjectDocumentListApi} from "@/api/project";
import {ProjectDocument, ProjectDocumentListParam} from "@/api/project/type.ts";

// 选择器显示状态
const colorSelectorVisible = ref(false)
const projectSelectorVisible = ref(false)

// 选中的数据
const selectedColor = ref<Color>()
const selectedProject = ref<ProjectDocument | null>(null)

// 颜色档案配置
const colorSearchFields: Array<{
  label: string
  prop: string
  type: 'input' | 'select'
  options?: Array<{ label: string; value: any }>
}> = [
  { label: '颜色编码', prop: 'colorCode', type: 'input' },
  { label: '颜色名称', prop: 'colorName', type: 'input' },
  {
    label: '状态',
    prop: 'isActive',
    type: 'select',
    options: [
      { label: '启用', value: '0' },
      { label: '禁用', value: '1' },
    ],
  },
]

const colorTableColumns = [
  { prop: 'colorCode', label: '颜色编码', width: 120 },
  { prop: 'colorName', label: '颜色名称', width: 120 },
  { prop: 'description', label: '描述' },
]

// 客户档案配置
// 项目状态映射
const statusOptions = [
  { value: 0, label: '进行中' },
  { value: 1, label: '已完成' },
  { value: 2, label: '已暂停' },
  { value: 3, label: '已取消' },
]
// 项目选择器搜索字段配置
const projectSearchFields = [
  { label: '项目名称', prop: 'name', type: 'input' as const },
  { label: '项目编号', prop: 'code', type: 'input' as const },
  { label: '客户名称', prop: 'customer', type: 'input' as const },
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: statusOptions,
  },
]

// 项目选择器表格列配置
const projectTableColumns = [
  { prop: 'name', label: '项目名称', width: 250 },
  { prop: 'code', label: '项目编号', width: 250 },
  { prop: 'customer', label: '客户名称', width: 250 },
  { prop: 'manager', label: '项目经理', width: 200 },
]


// 显示选择器
const showColorSelector = () => {
  if (props.mode === 'view') return // 查看模式不允许选择
  colorSelectorVisible.value = true
}

const openProjectSelector = () => {
  if (props.mode === 'view') return // 查看模式不允许选择
  projectSelectorVisible.value = true
}

// 处理选择结果
const handleColorSelect = (color: Color) => {
  selectedColor.value = color
  formData.color = color.colorName
  formData.colorPrice = 0
  getSpecificationDetail(true)
}

// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project
  console.log('选择的项目:', project)
  formData.projectId = project.id
}



// API 封装
const getColorList = (params: any) => {
  return getColorListApi(params)
}

// 获取项目列表数据的API方法
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10,
    }

    // 调用项目列表API - 使用真实API
    return await getProjectDocumentListApi(queryParams)
  } catch (error) {
    console.error('获取项目列表失败:', error)
    return { data: { list: [], total: 0 } }
  }
}
</script>

<template>
  <div class="bom-form">
    <div class="form-header">
      <h3>{{ mode === 'add' ? '新增核价单' : mode === 'edit' ? '编辑核价单' : '核价单详情' }}</h3>
    </div>

    <el-form ref="formRef"
             :model="formData"
             label-width="90px"
    :rules="rules">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="物料名称"
                        prop="name">
            <el-select v-model="formData.name"
                       placeholder="请选择物料名称"
                       :disabled="mode === 'view'"
                       :loading="bomLoading"
                       filterable
                       clearable
                       @change="handleMaterialChange"
                       @blur="handleMaterialAutoSelect"
                       style="width: 100%">
              <el-option
                v-for="item in bomList"
                :key="item.materialName"
                :label="item.materialName"
                :value="item.materialName">
                <span style="float: left">{{ item.materialName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                  {{ item.materialSpecifications }}
                </span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="物料型号" prop="specification">
            <el-input v-model="formData.specification"
                      placeholder="请输入物料型号"
                      :disabled="mode === 'view'"
                      @blur="() => getSpecificationDetail(true)" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="宽度" prop="width">
            <el-input v-model="formData.width"
                      :disabled="mode === 'view'"
                      @blur="() => getSpecificationDetail(true)">
              <template #append>mm</template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="高度" prop="height">
            <el-input v-model="formData.height"
                      :disabled="mode === 'view'"
                      @blur="() => getSpecificationDetail(true)">
              <template #append>mm</template>
            </el-input>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="材质" prop="material">
            <el-input v-model="formData.material"
                      :disabled="mode === 'view'" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="数量" prop="quantity">
            <el-input-number v-model="formData.quantity"
                             style="width: 260px"
                             :min="0"
                             :precision="2"
                             :disabled="mode === 'view'"
                             @change="() => getSpecificationDetail(true)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单位" prop="unit">
            <el-input v-model="formData.unit"
                      :disabled="mode === 'view'" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="颜色"
                        prop="color">
            <el-input v-model="formData.color"
                      placeholder="请选择颜色"
                      readonly>
              <template #append>
                <el-button @click="showColorSelector" :disabled="mode === 'view'">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="含税单价"
                        prop="unitPrice">
            <el-input :value="formatPrice(formData.unitPrice)"
                      readonly />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="单重"
                        prop="unitWeight">
            <el-input :value="formatNumber(formData.unitWeight)"
                      readonly />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="公斤价"
                        prop="kgPrice">
            <el-input :value="formatPrice(formData.kgPrice)"
                      readonly />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="总重"
                        prop="totalWeight">
            <el-input :value="formatNumber(formData.totalWeight)"
                      readonly />
          </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="项目"
                        prop="projectId">
            <el-input :model-value="selectedProject ? selectedProject.name : ''"
                      placeholder="请选择项目"
                      readonly>
              <template #append>
                <el-button @click="openProjectSelector" :disabled="mode === 'view'">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="颜色价格"
                        v-if="formData.color!='标准色' && formData.color">
            <el-input type="number"
                      v-model="formData.colorPrice"
                      placeholder="请输入颜色价格"
                      :disabled="mode === 'view'"
                      @blur="() => getSpecificationDetail(true)">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="包装费系数">
            <el-input type="number"
                      v-model="formData.packingPriceCoefficient"
                      placeholder="请输入包装费系数"
                      :disabled="mode === 'view'"
                      @blur="calculateFinalPrice">
              <template #append>元/kg</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6"
                >
          <el-form-item label="总价"
                        prop="totalPrice">
            <el-input :value="formatPrice(formData.totalPrice)"
                      readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="额外内容一">
            <el-input type="remark1"
                      v-model="formData.remark1"
                      placeholder="请输入额外内容一"
                      :disabled="mode === 'view'"
                       @blur="() => getSpecificationDetail(true)"
                     >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="额外内容二">
            <el-input type="remark2"
                      v-model="formData.remark2"
                      placeholder="请输入额外内容二"
                      :disabled="mode === 'view'"
                      @blur="() => getSpecificationDetail(true)"
                     >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="额外内容三">
            <el-input type="remark3"
                      v-model="formData.remark3"
                      placeholder="请输入额外内容三"
                      :disabled="mode === 'view'"
                      @blur="() => getSpecificationDetail(true)">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="紧固件@材质需求">
            <el-input type="fastenerType"
                      v-model="formData.fastenerType"
                      placeholder="请输入紧固件@材质需求"
                      :disabled="mode === 'view'"
                      @blur="() => getSpecificationDetail(true)">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- 分摊费用部分 -->
      <div v-if="mode == 'view'"
           class="share-section">
        <div class="share-title">
          <el-divider content-position="left">
            <el-icon>
              <Money />
            </el-icon>
            <span>分摊费用</span>
          </el-divider>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="包装费">
              <el-input :value="formatPrice(currentPackingFee)"
                        readonly>
                <template #append>
                  <span class="unit">元</span>
                </template>
                <template #prefix>
                  <el-icon>
                    <Box />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="运输费">
              <el-input :value="formatPrice(formData.transportationPrice)"
                        readonly>
                <template #append>
                  <span class="unit">元</span>
                </template>
                <template #prefix>
                  <el-icon>
                    <Van />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实施费">
              <el-input :value="formatPrice(formData.implementationPrice)"
                        readonly>
                <template #append>
                  <span class="unit">元</span>
                </template>
                <template #prefix>
                  <el-icon>
                    <SetUp />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="其他费用">
              <el-input :value="formatPrice(formData.otherPrice)"
                        readonly>
                <template #append>
                  <span class="unit">元</span>
                </template>
                <template #prefix>
                  <el-icon>
                    <More />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 使用tabs替换原来的两个表格 -->
      <el-tabs v-model="activeTab">
        <!-- 物料清单tab -->
        <el-tab-pane label="物料清单"
                     name="materials">
          <el-form-item prop="bomMaterialDtoList">
            <el-table :data="formData.children"
                      border
                      style="width: 100%">
              <el-table-column type="index"
                               label="序号"
                               width="70" />
              <el-table-column prop="name"
                               label="名称"
                               min-width="120" />
              <el-table-column prop="specification"
                               label="规格"
                               min-width="120" />


              <el-table-column prop="material"
                               label="材质"
                               min-width="100" />
              <el-table-column prop="height"
                               label="高度"
                               min-width="100" />
              <el-table-column prop="width"
                               label="宽度"
                               min-width="100" />
              <!--<el-table-column prop="unit" label="单位" width="80" />-->
              <el-table-column prop="quantity"
                               label="数量"
                               width="120">
                <template #default="scope">
                  {{ formatNumber(scope.row.quantity) }}
                </template>
              </el-table-column>
              <el-table-column prop="unitPrice"
                               label="含税单价"
                               min-width="100">
                <template #default="scope">
                  {{ formatPrice(scope.row.unitPrice) }}
                </template>
              </el-table-column>
    
              <el-table-column prop="unitWeight"
                               label="单重"
                               min-width="100">
                <template #default="scope">
                  {{ formatNumber(scope.row.unitWeight) }}
                </template>
              </el-table-column>
              <el-table-column label="操作"
                               width="80">
                <template #default="scope">
                  <el-button type="primary"
                             link
                             @click="viewDetail(scope.$index)"
                             icon="view" />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <el-form-item label="备注">
        <el-input v-model="formData.remark"
                  type="textarea"
                  :rows="3"
                  :disabled="mode === 'view'"
                  placeholder="输入描述" />
      </el-form-item>
    </el-form>

    <div class="form-actions">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary"
                 @click="submitForm"
                 v-if="mode !== 'view'">保存
      </el-button>
      <el-button type="success" @click="printPage">打印</el-button>
    </div>



    <!-- 颜色选择器（单选） -->
    <ArchiveSelector v-model="colorSelectorVisible"
                     title="选择颜色"
                     :search-fields="colorSearchFields"
                     :table-columns="colorTableColumns"
                     :fetch-data-api="getColorList"
                     :multiple="false"
                     :disabled="mode === 'view'"
                     @confirm="handleColorSelect" />



    <!-- 项目选择器组件 -->
    <ArchiveSelector v-model="projectSelectorVisible"
                     title="选择项目"
                     :search-fields="projectSearchFields"
                     :table-columns="projectTableColumns"
                     :fetch-data-api="getProjectList"
                     :multiple="false"
                     :disabled="mode === 'view'"
                     @confirm="handleProjectSelect" />




    <!-- 详情 -->
    <sys-dialog :title="dialog.title"
                :width="dialog.width"
                :visible="dialog.visible"
                :height="dialog.height"
                @onClose="onClose"
                @onConfirm="onClose">
      <template #content>
        <div class="detail-container"
             v-if="currentDetailData">
          <el-descriptions :column="2"
                           border>
            <template v-for="(value, key) in currentDetailData"
                      :key="key">
              <el-descriptions-item :label="(key as string).replace(/@/g, '')">
                {{ value }}
                <!-- 价格相关单位 -->
                <template v-if="(key as string).includes('总价') || (key as string).includes('费用')|| (key as string).includes('单价')">
                  <span class="unit">元</span>
                </template>
                
                <!-- 重量相关单位 -->
                <template v-else-if="(key as string).includes('总重') || (key as string).includes('单重')">
                  <span class="unit">kg</span>
                </template>
                
                <!-- 面积相关单位 -->
                <template v-else-if="(key as string).includes('单面积') || (key as string).includes('总面积')">
                  <span class="unit">m²</span>
                </template>

                <!-- 加工工艺单位 -->
                <template v-else-if="(key as string).includes('自动冲压') && !(key as string).includes('冲压')">
                  <span class="unit">元/kg</span>
                </template>
                <template v-else-if="(key as string).includes('冲压') || 
                                    (key as string).includes('钻孔') || 
                                    (key as string).includes('折弯') || 
                                    (key as string).includes('焊接') || 
                                    (key as string).includes('板材下料')">
                  <span class="unit">元/件</span>
                </template>
                <template v-else-if="(key as string).includes('辊轧成型') || 
                               (key as string).includes('切管下料') || 
                               (key as string).includes('抛丸')">
                  <span class="unit">元/kg</span>
                </template>
                <template v-else-if="(key as string).includes('激光下料')|| 
                               (key as string).includes('喷涂')">
                  <span class="unit">元/m</span>
                </template>
                <template v-else-if="(key as string).includes('剪板下料')">
                  <span class="unit">元/次</span>
                </template>
                <template v-else-if="(key as string).includes('长度') || (key as string).includes('厚度')">
                  <span class="unit">mm</span>
                </template>
                <template v-else-if="(key as string).includes('厚度')">
                  <span class="unit">m</span>
                </template>
              </el-descriptions-item>
            </template>
          </el-descriptions>
        </div>
      </template>
    </sys-dialog>
  </div>
</template>

<style scoped lang="scss">

@media print {
  .form-actions,
  .el-button,
  .el-tabs__header,
  .el-form-item__label {
    display: none !important;
  }
  /* 隐藏菜单栏 */
  .sidebar {
    display: none !important;
  }

  /* 隐藏页签 */
  .tabs {
    display: none !important;
  }

  /* 隐藏其他不需要的元素，例如标签栏 */
  .el-tabs__header {
    display: none !important;
  }

  .el-table {
    width: 100% !important;
    border-collapse: collapse;
  }

  .el-table th,
  .el-table td {
    border: 1px solid #000;
    padding: 8px;
  }

  .el-icon,
  .unit {
    display: none;
  }

  .bom-form {
    width: 100%;
    margin: 0;
    padding: 0;
  }
}



.bom-form {
  padding: 20px;
  padding-top: 0;
  background: #fff;
  height: 100%;
  overflow-y: auto;

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;

    h3 {
      margin: 0;
      font-size: 18px;
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }

  // 修改禁用状态下的样式
  :deep(.el-input.is-disabled .el-input__wrapper) {
    background-color: var(
      --el-input-disabled-bg-color,
      var(--el-disabled-bg-color)
    );
  }

  :deep(.el-input.is-disabled .el-input__inner) {
    color: var(--el-text-color-primary);
    -webkit-text-fill-color: var(--el-text-color-primary);
  }

  :deep(.el-textarea.is-disabled .el-textarea__inner) {
    color: var(--el-text-color-primary);
    -webkit-text-fill-color: var(--el-text-color-primary);
  }

  :deep(.el-radio.is-disabled.is-checked) {
    .el-radio__label {
      color: var(--el-text-color-primary);
    }
  }

  :deep(.el-radio.is-disabled) {
    .el-radio__label {
      color: var(--el-text-color-primary);
    }
  }

  // 添加价格输入样式
  :deep(.el-input-group__append) {
    padding: 0 10px;
    background-color: var(--el-color-primary-light-8);
    color: var(--el-color-primary);
    font-weight: bold;
  }

  // 添加tabs相关样式
  :deep(.el-tabs__header) {
    margin-bottom: 15px;
  }

  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
  }

  :deep(.el-tabs__item) {
    font-size: 14px;
    height: 40px;
    line-height: 40px;
  }

  :deep(.el-tabs__item.is-active) {
    font-weight: bold;
  }
}

.detail-container {
  padding: 20px;

  :deep(.el-descriptions) {
    margin-bottom: 20px;

    .el-descriptions__header {
      margin-bottom: 20px;
    }

    .el-descriptions__label {
      font-weight: bold;
      color: var(--el-text-color-primary);
      background-color: var(--el-fill-color-light);
      min-width: 150px;
    }

    .el-descriptions__content {
      font-size: 14px;
      color: var(--el-text-color-regular);

      .unit {
        margin-left: 4px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }
}

.share-section {
  margin-top: 20px;
  padding: 0 10px;

  .share-title {
    margin-bottom: 20px;

    .el-divider {
      .el-icon {
        margin-right: 8px;
        color: var(--el-color-primary);
      }

      span {
        font-size: 16px;
        font-weight: bold;
        color: var(--el-text-color-primary);
      }
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 22px;

    .el-form-item__label {
      font-weight: bold;
      color: var(--el-text-color-regular);
    }

    .el-input {
      .el-input__wrapper {
        background-color: var(--el-fill-color-blank);
      }

      .el-input__prefix {
        color: var(--el-color-primary);
        margin-right: 8px;
      }

      .el-input__inner {
        color: var(--el-color-danger);
        font-weight: bold;
        text-align: right;
      }

      .el-input-group__append {
        padding: 0 12px;
        background-color: var(--el-color-primary-light-8);

        .unit {
          color: var(--el-color-primary);
          font-size: 13px;
          font-weight: bold;
        }
      }
    }
  }
}

// 自定义确认对话框样式
:deep(.custom-message-box) {
  .el-message-box__content {
    white-space: pre-line;
    line-height: 1.6;
  }
  
  .el-message-box__message {
    font-size: 14px;
    color: var(--el-text-color-primary);
  }
}
</style>
